<template>
    <el-text type="primary" size="large">
        <h1 class="my-h1">确认订单</h1>
    </el-text>

    <el-card class="my-card">
        <template #header>
            <el-text size="large">
                <el-icon size="20px">
                    <Location />
                </el-icon>
                收货信息
            </el-text>
        </template>
        <div>
            <el-form ref="orderForm" label-position="right" label-width="100px" :rules="rules"
                style="width: 460px;margin-left: 50px;" :model="order">
                <el-form-item label="收货人姓名" prop="name">
                    <el-input v-model="order.name" />
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="order.phone" />
                </el-form-item>
                <el-form-item label="收货地址" prop="address">
                    <el-input v-model="order.address" />
                </el-form-item>
            </el-form>
        </div>
    </el-card>

    <el-card class="my-card">
        <template #header>
            <el-text size="large">
                <el-icon size="20px">
                    <Sell />
                </el-icon>
                商品信息
            </el-text>
        </template>
        <div>
            <el-table :data="goodsData" style="width: 90%;margin: 0 auto;">
                <el-table-column label="商品信息" fixed="left">
                    <template #default="scope">
                        <el-row>
                            <el-col :span="4">
                                <el-image style="width: 100px; height: 100px;" :src="scope.row.goods.cover" fit="cover">
                                    <template #error>
                                        <div style="font-size: 30px;">
                                            <el-icon>
                                                <Picture />
                                            </el-icon>
                                        </div>
                                    </template>
                                </el-image>
                            </el-col>
                            <el-col :span="12" :offset="1">
                                <el-row><el-text truncated>
                                        <el-tooltip class="box-item" :content="scope.row.goods.name" placement="top-start">
                                            {{ scope.row.goods.name }}
                                        </el-tooltip>
                                    </el-text></el-row>
                                <el-row><el-text truncated>{{ scope.row.type.name }}</el-text></el-row>
                                <el-row><el-text truncated>{{ scope.row.goods.name }}</el-text></el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column prop="goods.price" label="单价 (元)" width="150" />
                <el-table-column prop="cart.num" label="数量" width="150" />
                <el-table-column label="小计" width="150">
                    <template #default="scope">
                        ￥{{ (scope.row.goods.price * scope.row.cart.num).toFixed(1) }}
                    </template>
                </el-table-column>
            </el-table>
            <el-row>
                <el-text size="large" style="margin: 10px 0;">订单备注（选填）</el-text>
                <el-input v-model="order.remark" type="textarea" maxlength="50" show-word-limit autosize placeholder="在此处输入备注内容" />
            </el-row>
        </div>
    </el-card>

    <el-card class="my-card" style="box-shadow: var(--el-box-shadow-dark);">
        <template #header>
            <el-text size="large">
                <el-icon size="20px">
                    <Finished />
                </el-icon>
                确认订单信息
            </el-text>
        </template>
        <div>
            <el-col style="margin: 10px auto;text-align: right;">
                <el-row style="margin: 20px 100px 20px 0;justify-content: flex-end;" tag="div">
                    <el-text style="width: 120px;">
                        合计：￥
                        <span style="color: var(--el-color-primary-dark-2);font:700 16px 微软雅黑;">
                            {{ order.total.toFixed(1) }}</span>
                    </el-text>
                </el-row>
                <el-row style="margin: 20px 100px 10px 0;justify-content: flex-end;">
                    <el-text>
                        收货人：{{ order.name + " " }}
                        <span v-if="order.phone">
                            {{ order.phone.substring(0, 3) + "****" + order.phone.substring(7, 11) }}
                        </span>

                        <br>

                        寄送至：{{ order.address }}
                    </el-text>
                </el-row>
            </el-col>


            <el-button type="primary" @click="submitOrder"
                style="margin: 12px 0 20px 85%;width: 120px;height: 50px;font: 700 20px 微软雅黑;">提交订单</el-button>
        </div>
    </el-card>


    <el-dialog v-model="dialogVisible" title="订单支付" width="30%" align-center style="border-radius: 10px;">
        <div>
            <el-row>
                <el-button class="pay" @click="pay" v-if="payType === '微信支付'">模拟微信支付</el-button>
                <el-button class="pay" @click="pay" v-else-if="payType === '支付宝支付'">模拟支付宝支付</el-button>
            </el-row>
            <el-row style="margin-top: 10px;">
                <el-radio-group v-model="payType" style="margin: 20px auto;">
                    <el-radio-button :label="'微信支付'">微信支付</el-radio-button>
                    <el-radio-button :label="'支付宝支付'">支付宝支付</el-radio-button>
                </el-radio-group>
            </el-row>
        </div>
    </el-dialog>
</template>

<script>
import { ElMessage, ElLoading } from 'element-plus';
import axios from 'axios';

axios.defaults.baseURL = '/api';


export default {
    data() {
        return {
            dialogVisible: false,
            payType: '微信支付',
            rules: {
                name: [
                    { required: true, message: '请输入用户名', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入联系电话', trigger: 'blur' },
                    { pattern: /1\d{10}/, message: '请输入正确的联系电话', trigger: 'blur' }
                ],
                address: [
                    { required: true, message: '请输入收货地址', trigger: 'blur' }
                ]
            },
            goodsData: [
                // {
                //     "cart": {
                //         "cid": 4,
                //         "uid": 11,
                //         "gid": 9,
                //         "num": 1,
                //         "createTime": "2023-12-26T01:08:42",
                //         "updateTime": "2023-12-26T01:08:42",
                //         "status": 1
                //     },
                //     "goods": {
                //         "gid": 9,
                //         "tid": 4,
                //         "name": "冰淇淋蛋糕",
                //         "cover": "img4.jpg",
                //         "image1": "\"\"",
                //         "image2": "\"\"",
                //         "price": 59.5,
                //         "intro": "商品描述",
                //         "stock": 70,
                //         "createTime": "2023-12-15T15:28:32",
                //         "updateTime": "2023-12-15T15:28:32",
                //         "status": 1
                //     },
                //     "type": {
                //         "tid": 4,
                //         "name": "冰淇淋系列",
                //         "createTime": "2023-12-26T15:04:49",
                //         "updateTime": "2023-12-26T15:04:49",
                //         "status": 1
                //     }
                // }
            ],
            order: {
                remark: '',
                name: this.$store.state.user.username,
                phone: this.$store.state.user.phone,
                address: '',
                total: 0,
            }
        }
    },
    created() {
        //取消登录状态，清空缓存user对象
        this.$store.state.isLogin = false;
        //触发自动登录，通过token重新获取user对象
        this.$store.state.isLogin = true;
    },
    beforeMount() {
        //解析get传参
        const search = window.location.search;
        const params = new URLSearchParams(search);
        params.forEach((value, key) => {
            if (key === 'goodsData') {
                this.goodsData = JSON.parse(value);
                //计算总价
                for (const i in this.goodsData) {
                    let orderItem = this.goodsData[i];
                    let num = undefined;
                    let price = undefined;
                    for (const k in orderItem) {
                        if (k === 'cart') num = orderItem[k]['num'];
                        if (k === 'goods') price = orderItem[k]['price'];
                        if (price !== undefined && num !== undefined) {
                            this.order.total += price * num;
                            break;
                        }
                    }
                }
            }
        });




    },
    methods: {
        submitOrder() {
            this.$refs.orderForm.validate((valid) => {
                if (valid) {
                    this.dialogVisible = true;
                } else {
                    ElMessage.info("有收货信息不符合要求 ");
                    return false;
                }
            });
        },
        pay() {
            const loading = ElLoading.service({
                lock: true,
                text: '正在提交订单',
                background: 'rgba(0, 0, 0, 0.7)',
            })
            const data = {
                uid: this.$store.state.user.uid,
                total: this.order.total,
                remark: this.order.remark,
                name: this.order.name,
                phone: this.order.phone,
                address: this.order.address,
            }
            const cartIds = [];
            for (const k in this.goodsData) {
                cartIds.push(this.goodsData[k].cart.cid);
            }
            axios.post('/order/' + cartIds, data)
                .then(result => {
                    if (result.data.code === 1) {
                        ElMessage.success("支付成功！！！");
                        this.$store.state.navActive = '/home';
                    }
                })
                .catch((err) => {
                    console.log(err);
                    ElMessage.error("订单提交异常：" + err);
                })
                .finally(() => {
                    loading.close()
                })

        }
    }
}
</script>

<style scoped>
.my-h1 {
    color: #000;
    text-align: center;
    font-size: 28px;
    margin: 10px 0;
}
.my-card {
    margin: 50px auto;
    width: 90%;
}

.pay {
    width: 300px;
    min-width: 300px;
    height: 300px;
    min-height: 300px;
    margin: 0 auto;
}
</style>